package month1;

import java.util.Deque;
import java.util.LinkedList;

public class KthSmallest230_05 {
    public static void main(String[] args) {
        System.out.println(kthSmallest(new TreeNode(new Integer[]{3, 1, 4, null, 2}), 1));
    }

    /**
     * 中序遍历
     * @param root
     * @param k
     * @return
     */
    static int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> stack = new LinkedList<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (--k == 0) {
                break;
            }
            root = root.right;
        }
        return root.val;
    }
}
